package com.whuan.student.repository;

import com.whuan.student.dataObject.Student;
import com.whuan.student.util.IDUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

public class StudentRepositoryClass {
    @PersistenceContext
    private EntityManager entityManager;

    public int batchInsert(List<Student> students) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO student(id, name) VALUES ");
        for(Student student : students) {
            sb.append("( ?, ?),");
        }
        String sql = sb.toString().substring(0, sb.length() - 1);
        Query query = entityManager.createNativeQuery(sql);
        int paramIndex = 1;
        for(Student student : students) {
            query.setParameter(paramIndex++, IDUtils.getStudentId());
            query.setParameter(paramIndex++, student.getStudentName());
        }
        return query.executeUpdate();
    }
}
